<!--
 *用户列表组件
 * @Author: 舒克
 * @Official Accounts: 氧化1028
 * @email: 143587623@qq.com
 * @github: https://gitee.com/KingSio
 * @Date: 2020-12-23 18:24:19
 * @LastEditTime: 2021-02-08 18:16:01
 * @FilePath: \Vue全栈后台\项目\vue_shop\src\components\user\Users1.vue
-->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <!--   <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb> -->
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加 clearable代表清空-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            placeholder="请输入内容"
          >
            <el-button
              @click="getUserList"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 点击关闭、打卡的一个按钮 -->
          <template slot-scope="scope"
            ><!-- 作用域插槽 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对方框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      width="30%"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的用户：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="(item,index) in rolesList" :key="index"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogClosed">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUsersData,
  addUsersData,
  getModifyUsersData,
  getUserStateChangedData,
  editUsersData,
  deleteUsersData,
  putUsersData
} from '@/api/home'
import {getRolesListData} from '@/api/powerApi'
export default {
  data() {
    return {
      queryInfo: {
        //需要发送给后端的参数，拿到用户列表
        query: '',
        pagenum: 1, //当前的页数
        pagesize: 2 //当前每页显示多少条数据
      },
      userlist: [], //保存用户列表数据
      total: 0, //用户条数
      addDialogVisible: false, //控制添加用户对方框的显示与隐藏
      editDialogVisible: false, //控制修改用户对话框的显示与隐藏
      //弹框表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //添加用户的表单//添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 3 到 15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 3 到 15个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 1, max: 11, message: '长度在 3 到 15个字符', trigger: 'blur' }
        ]
      },
      //修改用户的验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // { validator:checkEmail, trigger: 'blur' }
          { min: 6, max: 15, message: '长度在 3 到 15个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          //{ validator:checkMobile, trigger: 'blur' }
          { min: 1, max: 11, message: '长度在 3 到 15个字符', trigger: 'blur' }
        ]
      },
      //查询的用户信息对象
      editForm: {},
      setRoleDialogVisible: false, //控制分配权限的显示隐藏
      userInfo: {}, //保存需要被分配角色的数据
      rolesList: [] ,//所有角色的数据
      selectedRoleId:"",//选中的id值
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //获取用户列表数据
    async getUserList() {
      /*  let { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      }) */
      let params = { ...this.queryInfo } //解构获取data定义数据，作为参数传送
      let { data: res } = await getUsersData(params) //传参
      if (res.meta.status != 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total //条数
      console.log(res)
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听 页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听添加用户，关闭添加弹框，清空弹框的表单数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
      //this.addForm
    },
    //点击按钮添加用户
    addUser() {
      this.$refs.addFormRef.validate(async val => {
        console.log(val)
        if (!val) return //如果验证失败不可以添加
        //其它清空可以发起请求
        // const { data: res } = await this.$http.post('users', this.addForm)
        const { data: res } = await addUsersData(this.addForm) //接口，把表单借口数据，传参到接口
        if (res.meta.status != 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addDialogVisible = false //添加成功后关闭弹框
        this.getUserList() //然后重新获取数据进行更新表格
      })
    },
    //修改功能
    async showEditDialog(id) {
      //console.log(id)//获取到点击的id
      // const { data: res } = await this.$http.get(`users/${id}`) 没有封装api之前的写法
      //封装api后面的写法
      const { data: res } = await getModifyUsersData(id)
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('没有查到数据')
      }
      this.editForm = res.data //保存到这个对象上
      this.editDialogVisible = true //打开对话框
    },
    //修改功能-修改提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async val => {
        let data = {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        }
        if (!val) return
        //发起修改请求
        /*  const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          data
        ) */
        const { data: res } = await editUsersData(this.editForm.id, data)
        console.log(data)
        if (res.meta.status != 200) {
          return this.$message.error('修改用户失败')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新数据
        this.getUserList()
        //提示修改成功
        this.$message.success('修改用户成功')
      })
    },
    //修改功能-关闭对话框事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    //删除功能,根据id删除用户信息
    async removeUserById(id) {
      //弹框询问是否删除
      const confirmResult = await this.$confirm(
        '永久操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => {
        return error
      })
      //如果用户确认删除，则返回值为字符串 confirm
      //如果用户取消了，则返回值为cancel
      if (confirmResult != 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await deleteUsersData(id)
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('删除用户失败')
      }
      this.getUserList()
      this.$message.success('删除成功')
    },

    //分配权限功能
    async setRole(data) {
      this.userInfo = data
      //展示对话框之前，获取所有角色的列表数据
      const { data: res } = await getRolesListData()
     if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    //监听分配权限功能-确定事件
   async saveRoleInfo(){
      //先判断是否选中了该id
      if(!this.selectedRoleId){
        return this.$message.error("请选中要分配的角色")
      }
      /* 
      参数1：用户id，需要分配的用户id
      参数2：角色id,需要分配给用户角色的id
      */
     //如果参数放在body，就以对象的方式发送
     let params={
       rid:this.selectedRoleId,
     }
     console.log(params)
      const {data:res}=await putUsersData(this.userInfo.id,params)
      if (res.meta.status !== 200) {
        return this.$message.error("分配失败")
      }
      this.$message.success("分配成功")
      this.getUserList();//更新数据
      this.setRoleDialogVisible = false
    },
    //监听分配角色对话框的-关闭事件
    setRightDialogClosed(){
      //取消，关闭，就情况下拉的选中的数据
      this.selectedRoleId="",
      this.userInfo={};
       this.setRoleDialogVisible = false
    },
    //监听switch开关的状态
    async userStateChanged(userinfo) {
      console.log(userinfo)
      /*  const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      ) */

      //参数1：用户id,参数2开关状态，true/false
      const { data: res } = await getUserStateChangedData(
        userinfo.id,
        userinfo.mg_state
      )
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    }
  }
}
</script>
<style lang="less" scoped></style>
